#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'读写操作'

__author__ = '许文杰'

from io import StringIO
import pickle

# try:
#     f = open('/Users/wenjiexu/Desktop/hello.txt', 'r')
#     print(f.read())
# finally:
#     if f:
#         f.close()

# 标识符 'r': 读  'w': 写（会覆盖原有的内容） 'a': 写（不会覆盖原有的内容，直接在原有内容的后面拼接）
with open('/Users/wenjiexu/Desktop/hello.txt', 'w') as f:

    f.write('hello phthon\n')
    f.write('测试\n')

with open('/Users/wenjiexu/Desktop/hello.txt', 'a') as f:

    f.write('hello phthon\n')
    f.write('测试\n')

with open('/Users/wenjiexu/Desktop/hello.txt', 'r') as f:

    for line in f.readlines():
        print(line.strip())

def func1():
    f = StringIO() # StringIO 读写str  BytesIO 读写二进制数据
    f.write('hello')
    f.write(' ')
    f.write('world')
    print(f.getvalue())

def func2():
    f = StringIO('Hello!\nHi!\nGoodbye!')
    while True:
        s = f.readline()
        if s == '':
            break
        print(s.strip())

if __name__ == '__main__':

    func1()

    func2()

    import os
    print(os.name)
    print(os.uname())
    print(os.path)
    # 查看当前目录的绝对路径:
    print(os.path.abspath('.'))
    # 在某个目录下创建一个新目录，首先把新目录的完整路径表示出来:
    # print(os.path.join('/Users/michael', 'testdir'))
    # 拆分路径
    # print(os.path.split('/Users/wenjiexu/Desktop/hello.txt'))
    # 直接得到文件扩展名
    # print(os.path.splitext('/Users/wenjiexu/Desktop/hello.txt'))
    # 然后创建一个目录:
    # os.mkdir('/Users/michael/testdir')
    # 删掉一个目录:
    # os.rmdir('/Users/michael/testdir')
    # 对文件重命名:     # 删掉文件:os.remove('test.txt')
    os.rename('/Users/wenjiexu/Desktop/hello.txt', 'test.txt')
    # 列出当前目录下的所有目录
    # print(x for x in os.listdir('.') if os.path.isdir())
    # 列出所有的.py文件
    # print(x for x in os.listdir('.') if os.path.isfile(x) and os.path.split(x)[1] == '.py')

    # 序列化
    # d = dict(name='Bob', age=20, score=88)
    # f = open('dump.txt', 'wb')
    # pickle.dump(d, f)
    # f.close()

    # 反序列化
    # f1 = open('dump.txt', 'rb')
    # d1 = pickle.load(f1)
    # f1.close()
    # print(d1)

    import json

    # python对象 转为 json
    # d = dict(name='Bob', age=20, score=88)
    # json_str = json.dumps(d)
    # print(json_str)
    # json 转为 python对象
    # d2 = json.loads(json_str)
    # print(d2)

class Stu(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

def stuToDict(stu):
    return {'name':stu.name, 'age':stu.age, 'score':stu.score}

def dictToStu(dict):
    return Stu(dict['name'], dict['age'], dict['score'])

s = Stu('Bob', 20, 88)
print(json.dumps(s, default=stuToDict))
print(json.dumps(s, default=lambda obj:obj.__dict__))

json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dictToStu))

